package com.csi.utils;


import com.csi.domain.Role;
import com.csi.pojo.TokenState;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.List;
import java.util.UUID;

public class JWTUtils {

    private static String signature = "ddeaeb1eff19b852983bce3e88aa6cbc";

    /**
     * 生成token
     *
     * @param time
     * @param userId
     * @return
     */
    public static String createJWT(long time, int userId, List<Role> roles,String userNumber) {

        JwtBuilder jwtBuilder = Jwts.builder();

        String token = jwtBuilder.setHeaderParam("typ", "jwt")
                .setHeaderParam("alg", "HS256")
                .claim("userId", userId)
                .claim("roles", roles)
                .claim("userNumber",userNumber)
                .setSubject("jwt-token")
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256, signature)
                .compact();

        return token;
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static TokenState parseJWT(String token) {

        JwtParser parser = Jwts.parser();

        TokenState tokenState = new TokenState();

        Jws<Claims> claimsJws = null;

        try {
            claimsJws = parser.setSigningKey(signature).parseClaimsJws(token);
        } catch (ExpiredJwtException e) {
            // 超时异常
            tokenState.setNum(-1);
        } catch (UnsupportedJwtException e) {
            throw new RuntimeException(e);
        } catch (MalformedJwtException e) {
            throw new RuntimeException(e);
        } catch (SignatureException e) {
            // 签名异常
            tokenState.setNum(-2);
        } catch (IllegalArgumentException e) {

        }

        if (claimsJws != null){
            Claims claims = claimsJws.getBody();

            int userId = (int) claims.get("userId");

            tokenState.setUserId(userId);

            List<Role> roles = (List<Role>) claims.get("roles");

            tokenState.setRoles(roles);
        }

        return tokenState;
    }
}
